package com.cxy.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.cxy.Exception.DateException;
import com.cxy.Exception.EmailException;
import com.cxy.Exception.PasswordException;
import com.cxy.context.BaseContext;
import com.cxy.dto.*;
import com.cxy.entity.*;
import com.cxy.mapper.*;
import com.cxy.result.PageResult;
import com.cxy.service.UserService;
import com.cxy.utils.ExcelUtil;
import com.cxy.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
     private JavaMailSender javaMailSender;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private AccessMapper accessMapper;
    @Autowired
    private ByReviewUserMapper byReviewUserMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private InformationMapper informationMapper;
    @Autowired
    private ListRateMapper listRateMapper;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
       User user = userMapper.login(userLoginDTO);
       return user;
    }

    /**
     * 党员分页查询
     * @param pageDTO
     * @return
     */
    public PageResult page(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPage(),pageDTO.getPageSize());
        Page<User> users = userMapper.pageAndSelect(pageDTO);
        return new PageResult(users.getTotal(),users.getResult());
    }

    /**
     * 新增用户
     * @param userDTO
     */
    public void saveUser(UserDTO userDTO) {
        userMapper.saveUser(userDTO);
    }

    /**
     * 根据id查询党员信息
     * @param id
     * @return
     */
    public UserVO getById(Long id) {
        User user = userMapper.getById(id);
        UserVO userVO =new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }

    /**
     * 修改党员基本信息
     * @param allMessageDTO
     */
    public void update(AllMessageDTO allMessageDTO) {
        userMapper.update(allMessageDTO);
    }

    /**
     * 修改密码
     * @param id
     */
    public void updatePassword(Long id) {
        User userVO = userMapper.getById(id);
        AllMessageDTO allMessageDTO =new AllMessageDTO();
        BeanUtils.copyProperties(userVO,allMessageDTO);
        allMessageDTO.setId(id);
        allMessageDTO.setPassword("123456");
        userMapper.update(allMessageDTO);
    }


    /**
     * 导出用户模板信息
     * @param response
     */
    public void export(HttpServletResponse response, HttpServletRequest request)  {
        //基于模板文件创建新的excel文件
        try {
            ExcelUtil.solveRequestHead("党员数据.xlsx",response,request);
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/党员数据.xlsx");
            XSSFWorkbook excel =new XSSFWorkbook(in);
            //通过输出流excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据导入
     * @param file
     */
    public void dataImport(MultipartFile file) throws IOException {
        UserDTO userDTO =new UserDTO();
        //用workbook读取传递过来的文件的信息
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取sheet
        Sheet sheet =workbook.getSheetAt(0);
        //获得最后一行
        int lastRowNum = sheet.getLastRowNum();
        //进行遍历
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行
            Row row = sheet.getRow(i);
            //获取单元格
            String name = row.getCell(0).getStringCellValue();
            String gender = row.getCell(1).getStringCellValue();
            String phone = row.getCell(2).getStringCellValue();
            String email = row.getCell(3).getStringCellValue();
            String userType = row.getCell(4).getStringCellValue();

            userDTO.setName(name);
            userDTO.setGender(gender);
            userDTO.setPhone(phone);
            userDTO.setEmail(email);
            userDTO.setUserType(userType);

            userMapper.saveUser(userDTO);
        }
    }

    /**
     * 删除用户
     * @param ids
     */
    public void delete(List<Long> ids) {
        userMapper.delete(ids);
    }

    /**
     * 查询所有用户·
     * @return
     */
    public List<UserVO> select() {
       List<UserVO> userVOS= userMapper.select();
        return userVOS;
    }
                        //用户端所有业务功能
    /**
     * 发送验证码
     */
    public void sendEmailCode(String email) {
        List<UserVO> users = userMapper.select();
        for (UserVO user : users) {
            if (user.getEmail().equals(email)){
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(from);
                message.setTo(email);
                message.setSubject("党员量化评价");
                String code = RandomUtil.randomNumbers(4);//随机生成一个4为数的验证码
                message.setText("您本次找回密码的验证码为:"+code);
                String key="code"+email;
                if (redisTemplate.opsForValue().get(key)!=null){
                    throw new PasswordException("您的验证码有效，请不要重复发送");
                }
                redisTemplate.opsForValue().set(key,code,5,TimeUnit.MINUTES);
                javaMailSender.send(message);
                return;
              }
            }
            throw new EmailException("邮箱不存在");
        }

    /**
     * 输入验证码和修改密码
     * @param updatePassWordDTO
     */
    @Override
    public void reset(UpdatePassWordDTO updatePassWordDTO) {
        String email = updatePassWordDTO.getEmail();
        String key="code"+email;
        String code = (String) redisTemplate.opsForValue().get(key);
        if (updatePassWordDTO.getCode().equals(code)){
            User user = userMapper.selectEmail(email);
            AllMessageDTO allMessageDTO =new AllMessageDTO();
            BeanUtils.copyProperties(user,allMessageDTO);
            if (updatePassWordDTO.getPassword().equals(updatePassWordDTO.getAgainPassword())){
                allMessageDTO.setPassword(updatePassWordDTO.getPassword());
                userMapper.update(allMessageDTO);
                return;
            }
            throw new PasswordException("两次输入的密码不一致");
        }
        throw new PasswordException("验证码错误");
    }

    /**
     * 用户端修改密码
     * @param updatePassWordDTO
     */
    public void userUpdatePassWord(UpdatePassWordDTO updatePassWordDTO) {
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        AllMessageDTO allMessageDTO = new AllMessageDTO();
        if (updatePassWordDTO.getPassword().equals(updatePassWordDTO.getAgainPassword())){
            user.setPassword(updatePassWordDTO.getPassword());
            BeanUtils.copyProperties(user,allMessageDTO);
            userMapper.update(allMessageDTO);
        }else {
            throw new PasswordException("两次输入的密码不一致");
        }
    }

    /**
     * 查看当前用户的评议·任务
     * @return
     */
    public SeeAssessVO seeAssess() {
        //获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        //获取所有任务
        List<Task> tasks = taskMapper.selectAll();
        //创建SeeAssessVO对象
        SeeAssessVO seeAssessVO =new SeeAssessVO();
        //遍历所有任务
        for (Task task : tasks) {
           //如果任务的状态是进行中的
            if (task.getStatus().equals(Task.COMPLETE_STATUS)){
                //获取当前正在进行中的任务id
                Long taskId = task.getId();
                //将正在进行中的期数传给SeeAssessVO对象
                String dateNumber = task.getDateNumber();
                seeAssessVO.setDateNumber(dateNumber);
                //获取当前用户待评议的人数
                Long noNumber =  recordMapper.getNoNumber(userId,taskId);
                seeAssessVO.setNumber(noNumber);
                //通过当前登录用户id和正在进行中的任务id返回被评议人和评议的状态
                seeAssessVO.setList(recordMapper.seeAssess(userId,taskId));
            }
        }
        return seeAssessVO;
    }

    /**
     * 用户评议
     */
    public UserAssessVO assess(Long id) {
        //查询当前被评议用户的信息
        ByReviewUser byReviewUser = byReviewUserMapper.getById(id);
        //通过token获取当前用户id
        Long userId = BaseContext.getCurrentId();
        //通过id获取当前用户信息
        User user = userMapper.getById(userId);
        //创建返回被评议用户明细对象
        UserAssessVO userAssessVO =new UserAssessVO();
        //设置被评议用户id为通过id获取的被评议用户的id
        userAssessVO.setByReviewUser(byReviewUser.getByReviewUser());
        //获取所有任务信息
        List<DemandAndUserTypeVO> accesses = accessMapper.selectAll();
        //创建任务要求和任务类型的对象
        DemandAndAssessTypeVO demandAndAssessTypeVO =new DemandAndAssessTypeVO();
        //创建集合方便后期存储创建任务要求和任务类型的对象
        List<DemandAndAssessTypeVO>list=new ArrayList<>();
        //遍历任务的所有集合获取用户类型是否与当前登录用户类型一致，如果一致就将任务的用户类型和要求存储在任务要求和任务类型的对象中
        for (DemandAndUserTypeVO access : accesses) {
            if (user.getUserType().equals(access.getUserType())){
               demandAndAssessTypeVO.setDemand(access.getDemand());
               demandAndAssessTypeVO.setAccessType(access.getAccessType());
               //最后添加到集合中
               list.add(demandAndAssessTypeVO);
            }
        }
        userAssessVO.setDemandAndAssessTypeVOList(list);
        return userAssessVO;
    }

    /**
     * 用户评议打分(当前用户为支部书记)
     */
    public void mark(Long byReviewUserId,Double score) {
        //获取当前打分的用户
        Long userId = BaseContext.getCurrentId();
        //获取当前登录用户详细信息
        User user = userMapper.getById(userId);
        //创建InformationScoreDTO对象
        InformationScoreDTO scoreDTO =new InformationScoreDTO();
        //创建UpdateTaskDTO对象
        UpdateTaskDTO updateTaskDTO =new UpdateTaskDTO();
        //获取所有任务
        List<Task> tasks = taskMapper.selectAll();
        //遍历所有任务找出正在进行中的任务
        for (Task task : tasks) {
            if (task.getStatus().equals(Task.COMPLETE_STATUS)){
                //获得当前正在进行中的任务id
                Long taskId = task.getId();
                //修改评议信息管理的分数
                recordMapper.mark(score,byReviewUserId,userId,taskId);
                //这时需要给Information表中的分数进行修改
                if (user.getUserType().equals(User.GENERAL_PARTY)){
                   //通过被评议人的id获取当前评议人的详细信息
                    Information by = informationMapper.getById(byReviewUserId);
                    scoreDTO.setId(by.getId());
                    scoreDTO.setSecretaryScore(by.getSecretaryScore()+score);
                    scoreDTO.setGrossScore(by.getGrossScore()+score);
                    informationMapper.update(scoreDTO);
                    //判断当前登录用户评议的状态如果所有评议的状态是"已完成"则评议任务中完成评议人数加一，未完成人数减一
                    List<ByAndStatusVO> vos = recordMapper.seeAssess(userId, taskId);
                    for (ByAndStatusVO vo : vos) {
                        if (vo.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                                return;
                        }
                    }
                    updateTaskDTO.setId(taskId);
                    updateTaskDTO.setAssessNumber(task.getAssessNumber()-1);
                    updateTaskDTO.setCompleteAssess(task.getCompleteAssess()+1);

                    taskMapper.update(updateTaskDTO);


                    List<Record> records = recordMapper.selectAll(taskId);
                    for (Record record : records) {
                        if (record.getByReviewUserId().equals(byReviewUserId)){
                            //获取该被评议用户的状态
                            if (record.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                                return;
                            }
                        }
                    }
                    //获得information表中的所有信息
                    List<Information> informations = informationMapper.selectAll();
                    InformationImportDTO informationDTO =new InformationImportDTO();
                    for (Information information : informations) {
                        if (information.getUserId().equals(byReviewUserId)){
                            informationDTO.setUserId(byReviewUserId);
                            informationDTO.setStatus(Information.COMPLETE_STATUS);
                            informationDTO.setTaskId(taskId);
                            informationMapper.importUpdate(informationDTO);
                        }
                    }

                        //当前用户为支部书记
                }else if (user.getUserType().equals(User.BRANCH_PARTY)){
                    //通过被评议人的id获取当前评议人的详细信息
                    Information by = informationMapper.getById(byReviewUserId);
                    scoreDTO.setId(by.getId());
                    scoreDTO.setBranchScore(by.getBranchScore()+score);
                    scoreDTO.setGrossScore(by.getGrossScore()+score);
                    informationMapper.update(scoreDTO);
                    //判断当前登录用户评议的状态如果所有评议的状态是"已完成"则评议任务中完成评议人数加一，未完成人数减一
                    List<ByAndStatusVO> vos = recordMapper.seeAssess(userId, taskId);
                    for (ByAndStatusVO vo : vos) {
                        if (vo.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                                return;
                        }
                    }
                    updateTaskDTO.setId(taskId);
                    updateTaskDTO.setAssessNumber(task.getAssessNumber()-1);
                    updateTaskDTO.setCompleteAssess(task.getCompleteAssess()+1);

                    taskMapper.update(updateTaskDTO);

                    List<Record> records = recordMapper.selectAll(taskId);
                    for (Record record : records) {
                        if (record.getByReviewUserId().equals(byReviewUserId)){
                            //获取该被评议用户的状态
                            if (record.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                                return;
                            }
                        }
                    }
                    //获得information表中的所有信息
                    List<Information> informations = informationMapper.selectAll();
                    InformationImportDTO informationDTO =new InformationImportDTO();
                    for (Information information : informations) {
                        if (information.getUserId().equals(byReviewUserId)){
                            informationDTO.setUserId(byReviewUserId);
                            informationDTO.setStatus(Information.COMPLETE_STATUS);
                            informationDTO.setTaskId(taskId);
                            informationMapper.importUpdate(informationDTO);
                        }
                    }
                    //普通党员评议
                }else if (user.getUserType().equals(User.PARTY_MEMBER)){
                    //通过被评议人的id获取当前评议人的详细信息
                    Information by = informationMapper.getById(byReviewUserId);
                    scoreDTO.setId(by.getId());
                    scoreDTO.setDemocraticScore(by.getDemocraticScore()+score);
                    scoreDTO.setGrossScore(by.getGrossScore()+score);
                    informationMapper.update(scoreDTO);
                    //判断当前登录用户评议的状态如果所有评议的状态是"已完成"则评议任务中完成评议人数加一，未完成人数减一
                    List<ByAndStatusVO> vos = recordMapper.seeAssess(userId, taskId);
                    for (ByAndStatusVO vo : vos) {
                        if (vo.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                            return;
                        }
                    }
                    updateTaskDTO.setId(taskId);
                    updateTaskDTO.setAssessNumber(task.getAssessNumber()-1);
                    updateTaskDTO.setCompleteAssess(task.getCompleteAssess()+1);

                    taskMapper.update(updateTaskDTO);
                    //获得所有记录
                    List<Record> records = recordMapper.selectAll(taskId);
                    for (Record record : records) {
                        if (record.getByReviewUserId().equals(byReviewUserId)){
                            //获取该被评议用户的状态
                            if (record.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                                return;
                            }
                        }
                    }
                    //获得information表中的所有信息
                    List<Information> informations = informationMapper.selectAll();
                    InformationImportDTO informationDTO =new InformationImportDTO();
                    for (Information information : informations) {
                        if (information.getUserId().equals(byReviewUserId)){
                            informationDTO.setUserId(byReviewUserId);
                            informationDTO.setStatus(Information.COMPLETE_STATUS);
                            informationDTO.setTaskId(taskId);
                            informationMapper.importUpdate(informationDTO);
                        }
                    }
                    //支部委员评议
                }else if (user.getUserType().equals(User.BRANCH_COMMISSIONER)){
                    //通过被评议人的id获取当前评议人的详细信息
                    Information by = informationMapper.getById(byReviewUserId);
                    scoreDTO.setId(by.getId());
                    scoreDTO.setBranchScore(by.getBranchScore()+score);
                    scoreDTO.setGrossScore(by.getGrossScore()+score);
                    informationMapper.update(scoreDTO);
                    //判断当前登录用户评议的状态如果所有评议的状态是"已完成"则评议任务中完成评议人数加一，未完成人数减一
                    List<ByAndStatusVO> vos = recordMapper.seeAssess(userId, taskId);
                    for (ByAndStatusVO vo : vos) {
                        if (vo.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                            return;
                        }
                    }
                    updateTaskDTO.setId(taskId);
                    updateTaskDTO.setAssessNumber(task.getAssessNumber()-1);
                    updateTaskDTO.setCompleteAssess(task.getCompleteAssess()+1);

                    taskMapper.update(updateTaskDTO);
                    //获得所有记录
                    List<Record> records = recordMapper.selectAll(taskId);
                    for (Record record : records) {
                        if (record.getByReviewUserId().equals(byReviewUserId)){
                            //获取该被评议用户的状态
                            if (record.getStatus().equals(Record.NO_COMPLETE_STATUS)){
                                return;
                            }
                        }
                    }
                    //逻辑来到这里说明被评议的用户已经被评议完了
                    //获得information表中的所有信息
                    List<Information> informations = informationMapper.selectAll();
                    InformationImportDTO informationDTO =new InformationImportDTO();
                    for (Information information : informations) {
                        if (information.getUserId().equals(byReviewUserId)){
                            informationDTO.setUserId(byReviewUserId);
                            informationDTO.setStatus(Information.COMPLETE_STATUS);
                            informationDTO.setTaskId(taskId);
                            informationMapper.importUpdate(informationDTO);
                        }
                    }
                }

            }
            return;
        }

    }

    /**
     * 查看当前任务的评议记录
     * @param dateNumber
     * @return
     */
    public List<AssessRecordVO> seeAssessRecord(String dateNumber) {
        //获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        List<AssessRecordVO>list =  recordMapper.seeAssessRecord(userId,dateNumber);
        return list;
    }

    /**
     * 返回月榜（月榜默认显示最新生成的期数的榜单。）
     * @return
     */
    public MonthTopVO month() {
        //获取所有任务找出正在进行中的任务
        List<Task> tasks = taskMapper.selectAll();
        MonthTopVO monthTopVO =new MonthTopVO();
        for (Task task : tasks) {
            if (task.getStatus().equals(Task.COMPLETE_STATUS)){
                Long taskId = task.getId();
                Task taskHave = taskMapper.getById(taskId);
                LocalDate date =LocalDate.parse(taskHave.getDateNumber(),DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                String dateNumber = date.format(DateTimeFormatter.ofPattern("yyyy年MM月"));
                monthTopVO.setDateNumber(dateNumber);
                List<MonthVO> month = informationMapper.month(taskId);
                monthTopVO.setList(month);
            }

        }

        return monthTopVO;
    }

    /**
     * 返回季度榜(首页的季度榜默认显示的是距离当前上一个季度的榜单)
     * @return
     */
    public QuarterTopVO quarter() {
        //通过当前正在进行中任务的期数拿到上一季度的开始月和结束月
        String number = taskMapper.getDateNumber();
        LocalDate localDate = LocalDate.parse(number);
        LocalDate startQuarter = getStartQuarter(localDate);
        LocalDate lastQuarter = getLastQuarter(localDate);

        //通过上一季度的开始月和结束月获取上一季度的三个月
        List<String> season = taskMapper.getFreshlySeason(startQuarter, lastQuarter);
        if (season.size()<3){
            throw new DateException("您当前的任务太少了没法生成季榜v_v");
        }
        //通过期数获取该期数的id
        String s = season.get(0);
        String s1 =season.get(1);
        String s2 =season.get(2);
        List<Long> ids = taskMapper.getId(s, s1, s2);
        QuarterTopVO quarterTopVO =new QuarterTopVO();


        List<LocalDate>localDates=new ArrayList<>();
        //遍历每一个期数判断他们是否属于同一个季度
        for (String dateNumber : season) {
            LocalDate date =LocalDate.parse(dateNumber);
            localDates.add(date);
        }
        //获取年份判断他们是不是同一年的期数
        int year1=localDates.get(0).getYear();
        int year2=localDates.get(1).getYear();
        int year3=localDates.get(2).getYear();
        if (year1==year2&&year2==year3&&getQuarter(localDates.get(0))==getQuarter(localDates.get(1))&&getQuarter(localDates.get(1))==getQuarter(localDates.get(2))){
            //这三个日期属于同一个季度返回学生的名字和他们的成绩之和
            List<QuarterVO>list = informationMapper.getSumScore(ids);
            String start = startQuarter.format(DateTimeFormatter.ofPattern("yyyy年M月"));
            String last = lastQuarter.format(DateTimeFormatter.ofPattern("yyyy年M月"));
            quarterTopVO.setDateNumbers(start+"-"+last);
            quarterTopVO.setList(list);
        }else {
            throw new DateException("您当前的任务太少了没法生成季榜v_v");
        }

        return quarterTopVO;
    }
    //判断是不是同一个季数的方法
    private int getQuarter(LocalDate date){
        int monthValue=date.getMonthValue();
        if (monthValue >= 1 && monthValue <= 3) {
            return 1;
        } else if (monthValue >= 4 && monthValue <= 6) {
            return 2;
        } else if (monthValue >= 7 && monthValue <= 9) {
            return 3;
        } else {
            return 4;
        }
    }

    //获取当前正在进行中任务的上一季度的开始月
    private  LocalDate getLastQuarter(LocalDate  date) {
        int currentMonth = date.getMonthValue();
        int currentYear=date.getYear();
        int startMonth;
        if (currentMonth==1||currentMonth==2||currentMonth==3){
            startMonth=12;
            currentYear-=1;
        }else {
            startMonth = ((currentMonth - 1) / 3) * 3 ;
        }
        return LocalDate.of(currentYear, startMonth, 1);
    }
    //获取当前正在进行中任务的上一季度的结束月
    private  LocalDate getStartQuarter(LocalDate date) {
        int currentMonth = date.getMonthValue();
        int currentYear=date.getYear();
        int startMonth;
        if (currentMonth==1||currentMonth==2||currentMonth==3){
            startMonth=10;
            currentYear-=1;
        }else {
            startMonth = ((currentMonth - 1) / 3) * 3 -2;
        }
        LocalDate startOfQuarter = LocalDate.of(currentYear, startMonth, 1);
        return  startOfQuarter ;

    }

    /**
     * 往期榜单(月查询)
     */
    public MonthTopVO ageMonthTop(String YearAndMonth)  {
        //定义日期格式
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy'年'MM'月'");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        MonthTopVO monthTopVO = new MonthTopVO();

        try {
            //将原始字符串转换为date类型
            Date date = sdf1.parse(YearAndMonth);
            //将date类型转换为目标格式的字符串
            String dateNumber = sdf2.format(date);
            //根据期数查询该任务的id
            Long taskId = taskMapper.getMonthId(dateNumber);
            //根据期数id查询评议信息
            List<MonthVO> month = informationMapper.month(taskId);
            //创建MonthTopVO对象
            monthTopVO.setDateNumber(YearAndMonth);
            monthTopVO.setList(month);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return monthTopVO;
    }

    /**
     * 往期榜单（季查询）
     */
    public QuarterTopVO ageQuarterTop(String year, String season) {
        QuarterTopVO quarterTopVO =new QuarterTopVO();
        // 获取当前季度的三期期数，根据三期期数获取出三期的
        int startMonth;
        switch (season) {
            case "s1":
                startMonth = 1;
                break;
            case "s2":
                startMonth = 4;
                break;
            case "s3":
                startMonth = 7;
                break;
            case "s4":
                startMonth = 10;
                break;
            default:
                throw new IllegalArgumentException("季度参数参数错误，正确为s1,s2..");
        }
        List<String>dateNumbers=new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            if (season.equals("s4")){
                dateNumbers.add(year+"-"+(startMonth+i)+"-01");
            }else {
                dateNumbers.add(year+"-0"+(startMonth+i)+"-01");
            }
        }
        // 根据构造的评议期数，去查询数据库评议信息记录，看是否查询到3调记录
        List<Long> ids = taskMapper.getId(dateNumbers.get(0), dateNumbers.get(1), dateNumbers.get(2));
        if (ids.size()<3){
            throw new DateException("季度暂时未生成");
        }
        List<QuarterVO> list = informationMapper.getSumScore(ids);
        quarterTopVO.setList(list);
        return quarterTopVO;
    }
}
